/**
 * create by young (young2f@outlook.com) on 2020/10/30
 */


'use strict';
import styles from '../../User/Register.less';
import {Button, Form, Input, notification, Popover, Progress, Select} from 'antd';

import React from 'react';
import moment from 'moment';
import {EyeInvisibleOutline, EyeTwoTone} from '@ant-design/icons';
import ComponentBase from '../../../components/Base/ComponentBase';
import {FormField, FormLayout} from 'antd-extra';

const {Option} = Select;
const FormItem = Form.Item;
moment.locale('zh-cn');
const passwordStatusMap = {
  ok: <div className={styles.success}>强度：强</div>,
  pass: <div className={styles.warning}>强度：中</div>,
  poor: <div className={styles.error}>强度：太短</div>,
};

const passwordProgressMap = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};
@Form.create()
export default class ModalRegisterUser extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {
      confirmDirty: false,
      visible: false,
      help: '',
      prefix: '86',
    };
  }

  componentDidMount() {
    this.props.dispatch({type: 'role/findRoles', payload: {}})
      .then(res => {
        const {result} = res;
        this.setState({role: result});
      });
  }

  componentWillUnmount() {

  }

  getPasswordStatus = () => {
    const {form} = this.props;
    const value = form.getFieldValue('password');
    if (value && value.length > 9) {
      return 'ok';
    }
    if (value && value.length > 5) {
      return 'pass';
    }
    return 'poor';
  };

  handleConfirmBlur = e => {
    const {value} = e.target;
    const {confirmDirty} = this.state;
    this.setState({confirmDirty: confirmDirty || !!value});
  };

  checkConfirm = (rule, value, callback) => {
    const {form} = this.props;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次输入的密码不匹配!');
    } else {
      callback();
    }
  };

  checkPassword = (rule, value, callback) => {
    if (!value) {
      this.setState({
        help: '请输入密码！',
        visible: !!value,
      });
      callback('error');
    } else {
      this.setState({
        help: '',
      });
      const {visible, confirmDirty} = this.state;
      if (!visible) {
        this.setState({
          visible: !!value,
        });
      }
      if (value.length < 6) {
        callback('error');
      } else {
        const {form} = this.props;
        if (value && confirmDirty) {
          form.validateFields(['confirm'], {force: true});
        }
        callback();
      }
    }
  };

  changePrefix = value => {
    this.setState({
      prefix: value,
    });
  };

  renderPasswordProgress = () => {
    const {form} = this.props;
    const value = form.getFieldValue('password');
    const passwordStatus = this.getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  submit = () => {
    const {modalRef, dispatch, form, user} = this.props;
    form.validateFields((err, values) => {
      if (err) {
        const {code} = err;
        const {errors} = code;
        errors.forEach(item => {
          notification.error(item);
        });
        return;
      }
      const {role} = this.state;
      const _role = _.find(role, item => item.roleCode === values.roleCode);
      values.roleName = _role.roleName;
      const {password} = values;

      values.password = this.getCryptoPassword(password);

      if (user) {
        this.props.result(values);
        modalRef.close();
        return;
      }
      dispatch({type: 'user/findUser', payload: {username: values.username}})
        .then(res => {
          const {result} = res;
          if (result) {
            notification.error({message: '用户名已存在！'});
            return;
          }
          values.userType = 'user';
          this.props.result(values);
          modalRef.close();
        });

    });
  };
  getOption = () => {
    const {role} = this.state;
    if (!role) return null;
    const temp = [];
    role.map(item => {
      const {roleName, roleCode} = item;
      temp.push(
        <Option value={roleCode}>{roleName}</Option>,
      );
    });
    return temp;
  };

  render() {
    const {form, user = {}, update} = this.props;
    console.log('is admin', user);
    const {username, nickname, tenantName, password, isAdmin, roleCode} = user;

    const {help, visible} = this.state;

    let str = update ? '更新' : '注册';
    return (
      <div className={styles.main}>

        <FormLayout form={form} cols={1}>
          <FormField
            label={'公司名称'}
            name={'tenantName'}
            required={true}
            initialValue={tenantName}
          ><Input disabled={tenantName} size="large" placeholder="公司"/></FormField>
          <FormField
            label={'账户'}
            name={'username'}
            required={true}
          ><Input size="large" placeholder="账户"/></FormField>
          <FormField
            label={'用户姓名'}
            name={'nickname'}
            required={true}
          ><Input size="large" placeholder="用户姓名"/></FormField>
          <FormField
            label={'密码'}
            name={'password'}
            required={true}
          >
              <Input.Password size="large"
                              iconRender={visible => (visible ? <EyeTwoTone/> : <EyeInvisibleOutline/>)}
                              placeholder="至少6位密码，区分大小写"/>

          </FormField>
          {
            !password && <FormField
              label={'确认密码'}
              name={'cpassword'}
              required={true}
            ><Input.Password size="large" iconRender={visible => (visible ? <EyeTwoTone/> : <EyeInvisibleOutline/>)}
                             type="password" placeholder="确认密码"/></FormField>
          }
          <FormField
            label={'角色'}
            name={'roleCode'}
            required={true}

          >
            <Select
              style={{width: '100%'}}
              allowClear={true}
              size="large"
              disabled={!isAdmin}
            >
              {this.getOption()}
            </Select>
          </FormField>
        </FormLayout>

        <Button
          size="large"
          // loading={submitting}
          className={styles.submit}
          type="primary"
          // htmlType="submit"
          onClick={this.submit.bind(this)}
        >
          {str}
        </Button>
      </div>
    );
  }
}
